var common = require('../../common.js');
var app = getApp();
let videoAd=null;
let interstitialAd=null;
Page({
  data: {
    items:[],
    navitems: [],
    cates: [],
    init: {},
    // 卡片分页
    pages: [],
    // 加载状态
    loads: [],
    // 滚动存储
    scrolls: [],
    // 激活卡片
    current: 0,
    // 主区域高度
    xheight: 1000,
    // 用户信息
    userinfo: null,
    // 微信CODE
    wxcode: '',
    doLikeId: 0,
    doLikeIndex: 0,
    doLikeFlag: false,
    height:90,
    showadd:true,
    authIndex:9999,
    count:0
  },
  onShow:function(){
    if(app.globalData.cateReresh == true){
      app.globalData.cateReresh = false;
      wx.reLaunch({
        url: '../index/index'
      });
    }
  },
  onLoad: function (option) {
    // 收藏提示
    var showadd = wx.getStorageSync('showAdd');
    if (showadd == undefined || showadd == null || showadd.length == 0 ) {
      showadd = true;
      this.data.height=132
    } 
    this.setData({
      userinfo: wx.getStorageSync('uerInfo'),
      showadd: showadd,
      height: this.data.height
      });
    
    this.initLoad(option);
    this.getWxCode();
   
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-ca144edfc4d63ee9'
      })
      interstitialAd.onLoad(() => {

      })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(res => {
       
      })
    }
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-0bd5ae1b37c0e198'
      })
      videoAd.onLoad(() => {
      })
      videoAd.onError((err) => { })
      videoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          if (this.data.doLikeFlag) {
            // 正常播放结束，可以下发游戏奖励
            wx.request({
              url: app.globalData.baseUrl + "/blade-video/userlike/like",
              method: 'POST',
              data: {
                token: common.token,
                openid: wx.getStorageSync('userInfo').openid,
                videoId: this.data.doLikeId,
                appId: wx.getAccountInfoSync().miniProgram.appId
              },
              success: res => {
                if (res.data.code == 200) {
                  if (res.data.data == 1) {
                    this.data.items[this.data.current][this.data.doLikeIndex].like = 1;
                  } else {
                    this.data.items[this.data.current][this.data.doLikeIndex].like = 0;
                  }
                  this.setData({ items: this.data.items }); 
                  let { doLikeFlag } = this.data
                  this.setData({
                    doLikeFlag: false
                  })

                }
              }
            });
          }else if(this.data.authIndex!=9999){
            var videData=this.data.items[this.data.current][this.data.authIndex];
            let vlink = encodeURIComponent(videData.vlink);
            let thumb = encodeURIComponent(videData.thumb);
          wx.navigateTo({
            url: '../playList/index?video_id=' + videData.id + "&title=" + videData.title + "&click=" + videData.click + "&info=" + videData.info + "&avatar=" + videData.avatar + "&vlink=" + vlink + "&thumb=" + thumb + "&categoryId=" + this.data.cates[this.data.current].id + "&nickName=" + videData.nickname + "&src=" + videData.src + "&srcFlag=" + videData.srcflag  ,
          });
            this.data.authIndex = 9999
          } 

        } else {
          // 播放中途退出，不下发游戏奖励
          let { doLikeFlag } = this.data
          this.setData({
            doLikeFlag: false
          })
          
        }
      })
    }

  },
  onShow: function (){
    if (wx.getStorageSync('userInfo').openid != null && app.globalData.push!=1){
      setTimeout(function () {
        wx.showModal({
          title: '订阅提示',
          content: '订阅秦腔社，更新最新视频火速向您报告',
          success(res) {
            if (res.confirm) {
              wx.request({
                url: app.globalData.baseUrl + "/blade-system/routineuser/updateByOpenid",
                method: 'POST',
                data: {
                  openid: wx.getStorageSync('userInfo').openid,
                  appid: wx.getAccountInfoSync().miniProgram.appId,
                  "push": 1
                },
                success: res => {
                  if (res.data.code == 200) {
                    wx.requestSubscribeMessage({
                      tmplIds: ['h2Cs1IV6qD2LaGyNeoazoMTiRoBpxG-uF7saBph7pNs'],
                      success(res) { }
                    })
                  }
                }
              });

            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }, 3000)

    }
    
   
    if (app.globalData.goback == 1) {
      if (interstitialAd) {
        interstitialAd.show(() => { app.globalData.goback = 0 }).catch(() => {
          interstitialAd.load()
            .then(() => interstitialAd.show(() => { app.globalData.goback = 0 }))
            .catch(err => {
              console.log('插屏视频 广告显示失败')
            })
        })
      }
    }
  },
  onReady: function(){
    var system = wx.getSystemInfoSync();
    this.data.xheight = system.screenHeight;
  
    this.setData({
      xheight: this.data.xheight - 155,
      
    });
    if (interstitialAd) {
      interstitialAd.show().catch(() => {
        interstitialAd.load()
          .then(() => interstitialAd.show())
          .catch(err => {
            console.log('插屏视频 广告显示失败')
          })
      })
    }
  },
  getWxCode: function () {
    wx.login({
      success: res => {
        this.setData({
          wxcode: res.code
        });
      }
    });
  },
  initLoad: function (option) {
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.baseUrl + '/blade-system/application/init',
      data: {
        token: common.token,
        appId:wx.getAccountInfoSync().miniProgram.appId
      },
      method: 'POST',
      success: (res) => {
        if(wx.getStorageSync('cateList').length > 0){
          this.data.cates = wx.getStorageSync('cateList');
        }else{
          this.data.cates = res.data.data.cates;
        }
        this.data.init = res.data.data.init;
        for (var i = 0; i < this.data.cates.length; i++) {
          this.data.navitems.push(this.data.cates[i].name);
          this.data.pages.push(1);
          this.data.loads.push(3);
          this.data.scrolls.push(0);
          this.data.items.push([]);
        }
        this.setData({
          cates: this.data.cates,
          init: this.data.init,
          navitems: this.data.navitems,
          pages:this.data.pages,
          loads:this.data.loads,
          scrolls:this.data.scrolls,
          items:this.data.items
        });
        app.globalData.appInfo = this.data.init;   
        this.setData({
          adVideo: app.globalData.appInfo.adVideo,
        })    
        wx.hideLoading();
        this.dataLoad();
      }  
    });

    
  },
  dataLoad: function(isreload){
    if (!isreload) {
      this.data.loads.splice(this.data.current, 1, 1);
      this.setData({
        loads: this.data.loads
      });
    }
    let fan_id = wx.getStorageSync('userInfo').fan_id;
    wx.request({
      url: app.globalData.baseUrl +"/blade-video/video/list",
      method: 'GET',
      data: {
        token:common.token,
        categoryId: this.data.cates[this.data.current].id,
        current: this.data.pages[this.data.current],
        appid:wx.getAccountInfoSync().miniProgram.appId,
        fan_id: fan_id
      },
      success: res => {
        if (res.data.code == 200) {
          // 第一页
          if (this.data.pages[this.data.current] == 1) {
            this.data.items.splice(this.data.current, 1, res.data.data.records);
            this.setData({
              items: this.data.items
            });
          } else {
            this.data.items[this.data.current] = this.data.items[this.data.current].concat(res.data.data.records);
            this.setData({
              items: this.data.items
            });
          }
          // 页码增加
          this.data.pages[this.data.current]++;
          this.data.loads.splice(this.data.current, 1, 3);
          this.setData({
            pages: this.data.pages,
            loads: this.data.loads
          });
        } else if (res.data.code == 888) {
          this.data.items[this.data.current] = 'empty';
          this.data.loads.splice(this.data.current, 1, 4);
          this.setData({
            items: this.data.items,
            loads: this.data.loads
          });
        } else if (res.data.code == 999) {
          this.data.loads.splice(this.data.current, 1, 2);
          this.setData({
            loads: this.data.loads
          });
        }
      },
      complete: () => {
        if (isreload) {
          setTimeout(() => {
            this.selectComponent("#graceReload-" + this.data.current).endReload();
          }, 300)
        }
      }
    });
  },
  openCate: function () {
    wx.navigateTo({
      url: '../index/cate',
    });
  },
  navChange: function (e) {
    this.setData({
      current: e.detail
    });
  },
  swiperChange: function (e) {
    
    var index = e.detail.current;
    this.setData({
      current: index
    });
    if (this.data.loads[this.data.current] != 2 || this.data.loads[this.data.current] != 4) {
       this.dataLoad();
    }
  },
  // 加载更多
  scrollend: function (e) {
    
    if (this.data.loads[this.data.current] == 2 || this.data.loads[this.data.current] == 4) {
      return false;
    }
    this.dataLoad();
  },
  scroll: function (e) {
    if(this.data.count%30==0){
      if (interstitialAd) {
        interstitialAd.show(() => { app.globalData.goback = 0 }).catch(() => {
          interstitialAd.load()
            .then(() => interstitialAd.show(() => { app.globalData.goback = 0 }))
            .catch(err => {
              console.log('插屏视频 广告显示失败')
            })
        })
      }
    }
    this.data.count++;
    this.data.scrolls[this.data.current] = e.detail.scrollTop;
    this.setData({
      scrolls: this.data.scrolls
    });
  },
  touchstart: function (e) {
    var touchObj = {
      scrollTop: this.data.scrolls[this.data.current],
      moveY: e.changedTouches[0].pageY
    };
    this.selectComponent("#graceReload-" + this.data.current).touchstart(touchObj);
  },
  touchmove: function (e) {
    
    var touchObj = {
      scrollTop: this.data.scrolls[this.data.current],
      moveY: e.changedTouches[0].pageY
    };
    this.selectComponent("#graceReload-" + this.data.current).touchmove(touchObj);
  },
  touchend: function (e) {
    var touchObj = {
      scrollTop: this.data.scrolls[this.data.current],
      moveY: e.changedTouches[0].pageY
    };
    this.selectComponent("#graceReload-" + this.data.current).touchend(touchObj);
  },
  // 下拉刷新
  reload: function () {
    this.data.pages[this.data.current] = 1;
    this.data.loads.splice(this.data.current, 1, 3);
    this.setData({
      pages: this.data.pages,
      loads: this.data.loads
    });
    this.dataLoad(1);
  },
  // 分享视频
  onShareAppMessage: function (option) {
    var obj;
    let { init } = this.data
    console.info(init.shareOpen == 1)
    if (init.shareOpen == 1) {
      obj = {
        title: this.data.init.shareTitle,
        path: 'pages/index/index',
        imageUrl: this.data.init.shareIcon
      }
    } else {
      var video = this.data.items[option.target.dataset.vindex][option.target.dataset.index];
      obj = {
        title: video.title,
        path: 'pages/index/index?video_id =' + video.video_id,
        imageUrl: video.icon
      }
    }
    return obj;
  },
  openVideo:function(option){
    var that = this;
    if (option.currentTarget.dataset.urge==1){
      wx.showModal({
        title: '提示',
        content: '当前视频需要观看视频广告才可以浏览！',
        success(res) {
          if (res.confirm) {
            that.data.authIndex = option.currentTarget.dataset.index;
            if (videoAd) {
              videoAd.show()
                .catch(() => {
                  videoAd.load()
                    .then(() => videoAd.show())
                    .catch(err => {
                      console.log('激励视频 广告显示失败')
                    })
                })
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
let vlink = encodeURIComponent(option.currentTarget.dataset.vlink);
    let thumb = encodeURIComponent(option.currentTarget.dataset.thumb);
    wx.navigateTo({
      url: '../playList/index?video_id=' + option.currentTarget.dataset.vid + "&title=" + option.currentTarget.dataset.title + "&click=" + option.currentTarget.dataset.click + "&info=" + option.currentTarget.dataset.info + "&avatar=" + option.currentTarget.dataset.avatar + "&vlink=" + vlink + "&thumb=" + thumb + "&categoryId=" + this.data.cates[this.data.current].id + "&nickName=" + option.currentTarget.dataset.nickname + "&src=" + option.currentTarget.dataset.src + "&srcFlag=" + option.currentTarget.dataset.srcflag  ,
    });
    }
    
    
  },
  openDoLike: function (option) {
    let { doLikeFlag } = this.data
    this.setData({
      doLikeFlag: true
    })
    if (option.type) {
      this.data.doLikeId = option.currentTarget.dataset.id;
      this.data.doLikeIndex = option.currentTarget.dataset.index;
    }

  },
  off: function () {
    let { doLikeFlag } = this.data
    this.setData({
      doLikeFlag: false
    })
    let { fullscreenFlag } = this.data
    this.setData({
      fullscreenFlag: false
    })
  },
  doLike: function (option) {

    if (videoAd) {
      videoAd.show()
        .catch(() => {
          videoAd.load()
            .then(() => videoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
    }
  },
  loginForLike: function (e) {
    if (e.detail.userInfo) {
      var user = e.detail.userInfo;
      this.setData({
        isShowUserName: true,
        userInfo: e.detail.userInfo,
      })
      user.openid = app.globalData.openid;
      app._saveUserInfo(user);
      this.setData({ userinfo: user });
      var videoContext = wx.createVideoContext("video" + e.currentTarget.dataset.id, this);
      videoContext.pause()
      let { doLikeFlag } = this.data
      this.setData({
        doLikeFlag: true
      })
      if (e.type) {
        this.data.doLikeId = e.currentTarget.dataset.id;
        this.data.doLikeIndex = e.currentTarget.dataset.index;
      }
    } else {
      app._showSettingToast('登陆需要允许授权');
    }
  },
  // 隐藏提示
  hideAdd: function () {
    this.data.height=90
    this.setData({ showadd: false, height: this.data.height });
    wx.setStorageSync('showAdd', false);
  },
  goNotice:function(){
    this.setData({ showadd: false });
    wx.setStorageSync('showAdd', false);
    wx.navigateTo({
      url: '../../graceUI/weplug-add-tips/index',
    });
  }
})